package com.bootdo.common.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.List;
import java.util.Objects;

public class DocumentUtil {
    public static String setWidth (String oldStr) {
        Document document = Jsoup.parse(oldStr, "utf-8");
        Elements select = document.select("*");

        Document newDocument = new Document("utf-8");

        int k = 0;
        int length = select.size();
            for (Element one : select) {
                if (k > 3) {
                    if (one != null) {
                        String style = one.attr("style");
                        if ("img".equals(one.nodeName())) {
                            if (style != null) {
                                if (style.contains("width:100%")) {
                                    // 包含的话就跳过
                                } else {
                                    String regexWidth = "width(:|：)+\\s*[0-9]+?px";
                                    String regexHeight = "height(:|：)+\\s*[0-9]+?px";
                                    if (style.contains("width") || style.contains("height")) {
                                        style = style.replaceAll(regexWidth, "width:100%;").replaceAll(regexHeight, "height:auto");
                                    } else {
                                        style = style + ";width:100%;";
                                    }
                                    one.attr("style", style);
                                }
                            }
                        } else {
                            String style2 = one.attr("style");
                            if (style2.contains("width")) {
                                if (!style2.contains("width:100%")) {
                                    style2 = style2.replace("width", "width:100%;");
                                    one.attr("style", style2);
                                }
                            }

                        }

                        if  ((length - k) <= 2 && (Objects.equals(one.text(), "") || Objects.equals(one.text(), "\\n") || Objects.equals(one.text(), "<br>"))) {
                            continue;
                        }
                        newDocument.appendChild(one);
                    }
                }
                k++;
            }

        return newDocument.toString();
    }

    public static String setImgMaxWidth(String context) {
        if(StringUtils.isNotEmpty(context)){
            Document document =  Jsoup.parse(context);
            List<Element> elements =  document.getElementsByTag("img");
            for(Element element : elements){
                element.attr("style","max-width:100%;");
            }

            System.err.println(document.toString());
            return document.toString();
        }
        return null;
    }
}
